#include "Socket.hpp"
#include "protocol.hpp"


void GetInForStdin(int &x, int &y, char &oper)
{
    std::cout << "please Enter X# ";
    std::cin >> x;
    std::cout << "please Enter Y# ";
    std::cin >> y;
    std::cout << "please Enter oper# ";
    std::cin >> oper;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if(argc != 3){
        std::cerr << "Usage->" << argv[0] << "server_ip server_port" << std::endl;
        exit(USAGE_ERR);
    };

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 1. 定制协议
    std::unique_ptr<protocol> proto = std::make_unique<protocol>();

    // 2.创建套接字
    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildTcpClientSocket();

    // 3.创建连接
    InetAddr server(server_ip, server_port);
    if(client->Connect(server) != 0){
        std::cerr << "connect error";
        exit(CONNECT_ERR);
    }
    std::cout << "connect success" << std::endl;

    std::string req_package;
    std::string req_buffer;
    while(true){
        // 1.获取输入
        int x, y;
        char oper;
        GetInForStdin(x, y, oper);
        Request req(x, y, oper);

            // 2.构建请求字符串
        req_package = proto->BuildRequest(req);
        //int cnt = 3;
        //while(cnt--){
        //    int x, y;
        //    char oper;
        //    GetInForStdin(x, y, oper);
        //    Request req(x, y, oper);

        //    // 2.构建请求字符串
        //    req_package += proto->BuildRequest(req);
        //}
        //std::cout << "-------------req_package--------------------" << std::endl;
        //std::cout << req_package << std::endl;
        //std::cout << "-----------------------------------------" << std::endl;


        // 3.发送
        client->Send(req_package);

        //sleep(2);
        // 4.读取响应
        Response resp;
        proto->GetResponse(client, req_buffer, &resp);

        // 5.展示结果
        resp.ShowResult();
    }
    client->Close();

    return 0;
}